package com.bss.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

@Component
public class BackupUtil {

	private static final Logger LOGGER = Logger.getLogger(BackupUtil.class.getName());

	public static final String BACKUP_FOLDER = "D:" + File.separatorChar + "BSS-Backup";

	private String user = "root";

	private String password = "nopass";

	private String database = "bssnew";

	private String command = "mysqldump.exe";

	private String statusText;

	public void backup() {
		try {

			BackupUtil.LOGGER.info("Backup started " + new Date());

			new File(BackupUtil.BACKUP_FOLDER).mkdirs();

			String target = BackupUtil.BACKUP_FOLDER + "\\Backup-bssnew-" + this.getDate() + ".txt";
			String exec = this.command + " -u " + this.user + " --password=" + this.password + " --lock-tables=FALSE -r " + target
					+ " " + this.database;

			Process pp = Runtime.getRuntime().exec(exec);

			pp.waitFor();

			if (pp.exitValue() == 0) {
				this.statusText = "Backup successfull.Backup saved at: " + target.replace("\\", "\\\\");
			} else {
				this.statusText = "Backup failed due to unknown error ! Please contact system administrator";
			}
		} catch (Exception e) {
			this.statusText = "Error in backup: " + e.getMessage();
		}
		BackupUtil.LOGGER.info("Backup finished " + new Date() + ", Status: " + this.statusText);

	}

	public String getDate() {
		return new SimpleDateFormat("dd-MMM-yyyy").format(new Date());
	}

	class StreamReader implements Runnable {

		private InputStream iis;

		public StreamReader(InputStream iis) {
			this.iis = iis;
		}

		public void run() {
			BufferedReader br = new BufferedReader(new InputStreamReader(this.iis));
			String str = null;
			try {
				while ((str = br.readLine()) != null) {
					System.out.println(str);
				}
			} catch (IOException e) {
			}
		}
	}

	public void setStatusText(String statusText) {
		this.statusText = statusText;
	}

	public String getStatusText() {
		return this.statusText;
	}

}
